﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Valentia.Kinection.Configuration;

namespace Valentia.Kinection.Configuration.Manager
{
    public partial class RecordsGrid : UserControl
    {
        private BindingSource bindingSource;

        public String IDColumnPropertyName { get; private set; }

        public Object CurrentSelectedItemObject { get; private set; }

        /// <summary>
        /// Remove the column header border in the Aero theme in Vista,
        /// but keep it for other themes such as standard and classic.
        /// </summary>
        public DataGridViewHeaderBorderStyle ProperColumnHeadersBorderStyle
        {
            get
            {
                return (SystemFonts.MessageBoxFont.Name == "Segoe UI") ?
                DataGridViewHeaderBorderStyle.None :
                DataGridViewHeaderBorderStyle.Raised;
            }
        }

        public event EventHandler<GridRecordDoubleClickedArgs> GridRecordDoubleClicked;

        public RecordsGrid(Type dataSourceType, String idColumnPropertyName, params GridDispalyColumnInfo[] columns)
        {
            InitializeComponent();

            this.bindingSource = new System.Windows.Forms.BindingSource();//this.components);
            this.IDColumnPropertyName = String.Empty;

            this.dgView.AllowUserToAddRows = false;
            this.dgView.AllowUserToDeleteRows = false;
            this.dgView.AllowUserToOrderColumns = false;
            this.dgView.AllowUserToResizeRows = false;
            this.dgView.ReadOnly = false;

            this.dgView.RowHeadersVisible = true;
            this.dgView.ColumnHeadersHeight = 80;
            this.dgView.EnableHeadersVisualStyles = false;
            this.dgView.ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.False;
            this.dgView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(59, 97, 156);
            this.dgView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            this.dgView.ColumnHeadersDefaultCellStyle.Font = new Font("Microsoft Sans Serif", 9, FontStyle.Bold);



            //this.dgView.ColumnHeadersDefaultCellStyle.BackColor  = Color.Blue;
            this.dgView.DefaultCellStyle.BackColor = this.dgView.DefaultCellStyle.SelectionBackColor = Color.FromArgb(209, 234, 251);
            this.dgView.DefaultCellStyle.ForeColor = this.dgView.DefaultCellStyle.SelectionForeColor = Color.FromArgb(0, 78, 152);

            this.dgView.AlternatingRowsDefaultCellStyle.BackColor = this.dgView.AlternatingRowsDefaultCellStyle.SelectionBackColor = Color.FromArgb(189, 218, 238);
            this.dgView.AlternatingRowsDefaultCellStyle.ForeColor = this.dgView.AlternatingRowsDefaultCellStyle.SelectionForeColor = Color.FromArgb(0, 78, 152);

            this.dgView.ColumnHeadersBorderStyle = this.ProperColumnHeadersBorderStyle;

            this.AddDataSource(dataSourceType, idColumnPropertyName, columns);
        }

        private void dgView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (e.ColumnIndex < 0 || e.RowIndex < 0) return;

            if (e.RowIndex < 0) return;

            CurrentSelectedItemObject = this.bindingSource[e.RowIndex];
        }

        private void dgView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
            //String data = this.dgView[e.ColumnIndex, e.RowIndex].Value.ToString();

            if (this.GridRecordDoubleClicked != null) { this.GridRecordDoubleClicked(this, new GridRecordDoubleClickedArgs(this.bindingSource[e.RowIndex])); }
        }

        public void AddDataSource(Type dataSourceType, String idColumnPropertyName, params GridDispalyColumnInfo[] columns)
        {
            this.bindingSource.Clear();
            this.bindingSource.DataSource = null;

            this.dgView.Columns.Clear();
            this.dgView.DataSource = null;

            this.IDColumnPropertyName = idColumnPropertyName;

            //((System.ComponentModel.ISupportInitialize)(this.bindingSource)).BeginInit();

            this.bindingSource.DataSource = dataSourceType;
            this.dgView.DataSource = this.bindingSource;

            DataGridViewColumn[] currentColumns = new DataGridViewColumn[this.dgView.Columns.Count];
            this.dgView.Columns.CopyTo(currentColumns, 0);

            foreach (DataGridViewColumn aCol in this.dgView.Columns)
            {
                aCol.Visible = false;
                aCol.ReadOnly = true;
            }

            this.dgView.Columns[idColumnPropertyName].DisplayIndex = 0;
            this.dgView.Columns[idColumnPropertyName].Visible = false;

            for (int index = 0; index < columns.Length; index++)
            {
                DataGridViewColumn dgColumn = currentColumns.First(p => p.DataPropertyName == columns[index].DataPropertyName);
                dgColumn.DisplayIndex = (index + 1);
                dgColumn.Visible = true;
                dgColumn.HeaderText = columns[index].HeaderText;

                if (dataSourceType.Name == "UtilityUser")
                {
                    if (index == 0)
                    {
                        dgColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    }
                }
                else if (index == columns.Length - 1)
                {
                    dgColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
                //dgColumn.Index = (index + 1);
            }

            //this.dgView.Columns.Clear();
            //DataGridViewColumn dgColumn = new DataGridViewTextBoxColumn();
            //dgColumn.DataPropertyName = this.IDColumnPropertyName;
            //dgColumn.HeaderText = this.IDColumnPropertyName;
            //dgColumn.Name = this.IDColumnPropertyName;
            //dgColumn.Visible = false;

            //this.dgView.Columns.Add(dgColumn);

            //foreach (GridDispalyColumnInfo column in columns)
            //{
            //    dgColumn = new DataGridViewTextBoxColumn();
            //    dgColumn.DataPropertyName = column.DataPropertyName;
            //    dgColumn.HeaderText = column.HeaderText;
            //    dgColumn.Name = column.DataPropertyName;

            //    this.dgView.Columns.Add(dgColumn);
            //}

            //((System.ComponentModel.ISupportInitialize)(this.bindingSource)).EndInit();

            //if (this.dgView.Rows.Count == 0)
            //{
            //    updateToolStripMenuItem.Enabled = false;
            //    deleteAllToolStripMenuItem.Enabled = false;
            //    deleteToolStripMenuItem.Enabled = false;
            //}
            //else
            //{
            //    updateToolStripMenuItem.Enabled = true;
            //    deleteAllToolStripMenuItem.Enabled = true;
            //    deleteToolStripMenuItem.Enabled = true;
            //}
        }

        public void AddRecords(params object[] records)
        {
            this.bindingSource.Clear();
            foreach (Object obj in records) { this.bindingSource.Add(obj); }

            if (records != null && records.Length > 0)
            {
                dgView_CellClick(null, new DataGridViewCellEventArgs(0, 0));
            }
        }

        private void addToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frmConfigManager.currentSelectedControl == "Utility Users")
            {
                frmInsertUpdateUtilityUser addUpdateUtilityUser = new frmInsertUpdateUtilityUser(null);
                addUpdateUtilityUser.ShowDialog();

                AddRecords(ConfigurationHelper.GetAllUtilityUsers().ToArray());
            }
            else if (frmConfigManager.currentSelectedControl == "Service Users")
            {
                frmInsertUpdateDataUser addUpdateDataUser = new frmInsertUpdateDataUser(null);
                addUpdateDataUser.ShowDialog();

                AddRecords(ConfigurationHelper.GetAllDataUsers().ToArray());
            }
            else// if (frmConfigManager.currentSelectedControl == "Kinect Devices")
            {
                frmAddUpdateKinectDevice addUpdateKinectDevice = new frmAddUpdateKinectDevice(null);
                addUpdateKinectDevice.ShowDialog();

                AddRecords(ConfigurationHelper.GetAllKinectDevices().ToArray());
            }

        }

        private void updateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            #region Update Region

            #region Kinect Device

            if (frmConfigManager.currentSelectedControl == "Kinect Devices")
            {
                KinectDevice kinectDevice = (KinectDevice)this.CurrentSelectedItemObject;

                if (kinectDevice == null)
                {
                    MessageBox.Show("No record selected", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    frmAddUpdateKinectDevice addUpdateKinectDevice = new frmAddUpdateKinectDevice(kinectDevice);
                    addUpdateKinectDevice.ShowDialog();

                    AddRecords(ConfigurationHelper.GetAllKinectDevices().ToArray());
                }
                return;
            }

            #endregion

            #region Service Users

            else if (frmConfigManager.currentSelectedControl == "Service Users")
            {
                DataUser dataUser = (DataUser)this.CurrentSelectedItemObject;

                if (dataUser == null)
                {
                    MessageBox.Show("No record selected", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    frmInsertUpdateDataUser addUpdateDataUser = new frmInsertUpdateDataUser(dataUser);
                    addUpdateDataUser.ShowDialog();

                    AddRecords(ConfigurationHelper.GetAllDataUsers().ToArray());
                }
                return;
            }

            #endregion

            #region Utility Users

            //if (e.Item.Text.Equals("Update") && !btnUtilityUsers.Enabled)
            else if (frmConfigManager.currentSelectedControl == "Utility Users")
            {
                UtilityUser utilityUser = (UtilityUser)this.CurrentSelectedItemObject;
                //UtilityUser utilityUser = (UtilityUser)dgView.SelectedRows[0].DataGridView;

                if (utilityUser == null)
                {
                    MessageBox.Show("No record selected", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    frmInsertUpdateUtilityUser addUpdateUtilityUser = new frmInsertUpdateUtilityUser(utilityUser);
                    addUpdateUtilityUser.ShowDialog();

                    AddRecords(ConfigurationHelper.GetAllUtilityUsers().ToArray());

                }
                return;
            }

            #endregion

            #endregion
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            #region Delete Region

            #region Kinect Device

            if (frmConfigManager.currentSelectedControl == "Kinect Devices")
            {
                KinectDevice kinectDevice = (KinectDevice)this.CurrentSelectedItemObject;

                if (kinectDevice == null)
                {
                    MessageBox.Show("No record selected", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (MessageBox.Show("Are you sure, you want to delete kinect device?", Program.ApplicationName
                        , MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        if (ConfigurationHelper.DeleteKinectDeviceByName(kinectDevice.KinectDeviceName))
                        {
                            MessageBox.Show("Record deleted successfully.", Program.ApplicationName
                            , MessageBoxButtons.OK, MessageBoxIcon.Information);

                            AddRecords(ConfigurationHelper.GetAllKinectDevices().ToArray());
                        }
                        else
                        {
                            MessageBox.Show("Unable to delete record.", Program.ApplicationName
                            , MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                return;
            }

            #endregion

            #region Service Users

            else if (frmConfigManager.currentSelectedControl == "Service Users")
            {
                DataUser dataUser = (DataUser)this.CurrentSelectedItemObject;

                if (dataUser == null)
                {
                    MessageBox.Show("No record selected", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (MessageBox.Show("Are you sure, you want to delete service user?", Program.ApplicationName
                        , MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        if (ConfigurationHelper.DeleteDataUserByLoginName(dataUser.Login))
                        {
                            MessageBox.Show("Record deleted successfully.", Program.ApplicationName
                            , MessageBoxButtons.OK, MessageBoxIcon.Information);

                            AddRecords(ConfigurationHelper.GetAllDataUsers().ToArray());
                        }
                        else
                        {
                            MessageBox.Show("Unable to delete record.", Program.ApplicationName
                            , MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                return;
            }

            #endregion

            #region Utility Users

            else if (frmConfigManager.currentSelectedControl == "Utility Users")
            {
                UtilityUser utilityUser = (UtilityUser)this.CurrentSelectedItemObject;

                if (utilityUser == null)
                {
                    MessageBox.Show("No record selected", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (MessageBox.Show("Are you sure, you want to delete utility user?", Program.ApplicationName
                        , MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        if (ConfigurationHelper.DeleteUtilitiyUserByLoginName(utilityUser.Login))
                        {
                            MessageBox.Show("Record deleted successfully.", Program.ApplicationName
                            , MessageBoxButtons.OK, MessageBoxIcon.Information);

                            AddRecords(ConfigurationHelper.GetAllUtilityUsers().ToArray());
                        }
                        else
                        {
                            MessageBox.Show("Unable to delete record.", Program.ApplicationName
                            , MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                return;
            }

            #endregion

            #endregion
        }

        private void deleteAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            #region Delete All Region

            #region Kinect Device

            if (frmConfigManager.currentSelectedControl == "Kinect Devices")
            {
                if (MessageBox.Show("Are you sure, you want to delete all kinect devices?", Program.ApplicationName
                     , MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    if (ConfigurationHelper.DeleteAllKinectDevices())
                    {
                        MessageBox.Show("Records deleted successfully.", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Information);

                        AddRecords(ConfigurationHelper.GetAllKinectDevices().ToArray());
                    }
                    else
                    {
                        MessageBox.Show("Unable to delete records.", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                return;
            }

            #endregion

            #region Service Users

            else if (frmConfigManager.currentSelectedControl == "Service Users")
            {
                if (MessageBox.Show("Are you sure, you want to delete all service users?", Program.ApplicationName
                    , MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    if (ConfigurationHelper.DeleteAllDataUsers())
                    {
                        MessageBox.Show("Records deleted successfully.", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Information);

                        AddRecords(ConfigurationHelper.GetAllDataUsers().ToArray());
                    }
                    else
                    {
                        MessageBox.Show("Unable to delete records.", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                return;
            }

            #endregion

            #region Utility Users

            else if (frmConfigManager.currentSelectedControl == "Utility Users")
            {
                if (MessageBox.Show("Are you sure, you want to delete all utility users?", Program.ApplicationName
                    , MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    if (ConfigurationHelper.DeleteAllUtilityUsers())
                    {
                        MessageBox.Show("Records deleted successfully.", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Information);

                        AddRecords(ConfigurationHelper.GetAllUtilityUsers().ToArray());
                    }
                    else
                    {
                        MessageBox.Show("Unable to delete records.", Program.ApplicationName
                        , MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                }
                return;
            }

            #endregion

            #endregion
        }
    }
}